import 'dart:convert';

import 'package:excel_utils/pages/daily/daily_data_entry/bean/third_bean.dart';
import 'package:excel_utils/pages/daily/daily_data_entry/bloc/daily_data_entry_cubit.dart';
import 'package:excel_utils/repository/daily_entry/daily_entry_repository.dart';
import 'package:excel_utils/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class DailyDataEntryPage extends StatefulWidget {
  const DailyDataEntryPage({super.key});

  @override
  State<DailyDataEntryPage> createState() => _DailyDataEntryPageState();
}

class _DailyDataEntryPageState extends State<DailyDataEntryPage> {
  DailyDataEntryCubit? dailyDataEntryCubit;

  List<dynamic> loadingKeys = [];
  bool saveAllLoading = false;

  List<ThirdBean> thirdData = [];
  late DateTime? startDate;
  late DateTime? endDate;

  late DateTime startInitDate;
  late DateTime endInitDate;

  @override
  void initState() {


    DateTime now = DateTime.now();
    startInitDate = DateTime(now.year, now.month, 1);
    endInitDate = DateTime(now.year, now.month, now.day);
    startDate = startInitDate;
    endDate = endInitDate;

    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (BuildContext context) {
        return DailyDataEntryCubit(dailyEntryRepository: context.read<DailyEntryRepository>());
      },
      child: BlocBuilder<DailyDataEntryCubit, DailyDataEntryState>(
        builder: (BuildContext context, DailyDataEntryState state) {
          dailyDataEntryCubit = dailyDataEntryCubit ?? context.read<DailyDataEntryCubit>();
          if (state is DailyDataCreateDateState) {
            thirdData = state.thirdDatas;
            print(thirdData);
          } else if (state is DailyDataSaveAllLoadingState) {
            saveAllLoading = true;
          } else if (state is DailyDataEntrySuccessState) {
            saveAllLoading = false;
            thirdData=state.thirdData;
          }
          // 单个
          else if (state is DailyDataSaveSignLoadingState) {
            loadingKeys.add(state.key);
          } else if (state is DailyDataEntrySignSuccessState) {
            loadingKeys.remove(state.key);
          } else if (state is DailyDataEntrySignErrorState) {
            loadingKeys.remove(state.key);
          } else {}

          return buildUI();
        },
      ),
    );
  }

  Widget buildUI() {
    return Scaffold(
      body: Container(
        child: SingleChildScrollView(
          child: Column(
            children: [
              buildThirdDataEntryPage(),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.adb_rounded),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
    );
  }

  // 默认生成当月数据，然后从服务器获取整月的数据

  // 选择月份之后从服务器获取数据

  Widget buildThirdDataEntryPage() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("第三方数据录入"),
          // 选择日期
          // showDateRangePicker(context: context, firstDate: DateTime(2025, 7, 1), lastDate: DateTime(2025, 7, 31)),
          Text("日期范围"),
          TextButton(
              onPressed: () {
                if (startDate == null || endDate == null) return;
                dailyDataEntryCubit?.createDateData(thirdData: thirdData, startDate: startDate!, endDate: endDate!);
              },
              child: Text("生成日期数据")),
          calendarDatePicker(
              year: 2025,
              month: 7,
              day: 1,
              row: true,
              currentStartDate: startInitDate,
              currentEndDate: endInitDate,
              startOnDateChanged: (startTime, startDateTemp) {
                startDate = startDateTemp;
              },
              endOnDateChanged: (endTime, endDateTemp) {
                endDate = endDateTemp;
              }),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text("日期"),
              Flexible(child: Center(child: Text("電單車"))),
              Flexible(child: Center(child: Text("貨VAN"))),
              Flexible(child: Center(child: Text("頂北區司機/兵位包底數"))),
            ],
          ),

          ListView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(),
            itemCount: thirdData.length,
            itemBuilder: (BuildContext context, int index) {
              ThirdBean third = thirdData[index];
              return Padding(
                padding: const EdgeInsets.all(1.0),
                child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                  Text(third.createTimeStr.toString(), style: TextStyle(fontSize: 16, color: Colors.deepOrange)),
                  SizedBox(width: 10),
                  Flexible(
                    child: TextField(
                      controller: TextEditingController(text: third.skDdc),
                      decoration: const InputDecoration(
                        border: OutlineInputBorder(),
                      ),
                      onChanged: (value) {
                        // thirdData[entry.key]["skDdc"] = value;
                        thirdData[index].skDdc = value;
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Flexible(
                    child: TextField(
                      controller: TextEditingController(text: third.skHvan),
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                      ),
                      onChanged: (value) {
                        // thirdData[entry.key]["skHvan"] = value;
                        thirdData[index].skHvan = value;
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Flexible(
                    child: TextField(
                      controller: TextEditingController(text: third.skBqsjBwb),
                      decoration: InputDecoration(
                        border: OutlineInputBorder(),
                      ),
                      onChanged: (value) {
                        // thirdData[entry.key]["skBqsjBwb"] = value;
                        thirdData[index].skBqsjBwb = value;
                      },
                    ),
                  ),
                  SizedBox(width: 10),
                  Container(
                    width: 100,
                    child: loadingKeys.contains(third.createTimeStr)
                        ? Center(child: CircularProgressIndicator())
                        : TextButton(
                            onPressed: () {
                              dailyDataEntryCubit?.saveSignData(thirdData: thirdData,thirdBean: thirdData[index]);
                            },
                            child: Text("Save")),
                  ),
                ]),
              );
            },
          ),

          SizedBox(height: 10),
          if (saveAllLoading)
            Center(child: CircularProgressIndicator())
          else
            TextButton(
                onPressed: () {
                  print(thirdData);
                  // List<ThirdBean> thirdBeans = [];
                  // thirdData.forEach((key, value) {
                  //   ThirdBean thirdBean = ThirdBean(
                  //     createTime: "$key 00:00:00",
                  //     createTimeStr: key,
                  //     skDdc: value["skDdc"],
                  //     skHvan: value["skHvan"],
                  //     skBqsjBwb: value["skBqsjBwb"],
                  //   );
                  //   if (value["id"] != null && value["id"] != "") {
                  //     thirdBean.id = value["id"];
                  //   }
                  //   thirdBeans.add(thirdBean);
                  // });
                  dailyDataEntryCubit?.saveAllData(thirdData: thirdData);
                },
                child: Text("All Save")),
          SizedBox(height: 10),
        ],
      ),
    );
  }

}
